
package com.trial.area.common.controller;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Date;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * 图片验证码生成请求
 *
 * @author 朱国军
 * @since 1.0
 * @version 2016年3月25日 朱国军
 */
@Controller
public class ImageCodeController extends BaseController {

    private Logger logger = LoggerFactory.getLogger(ImageCodeController.class);
    
    /**
     * 图片验证码生成请求
     *
     * @param pageId 页面标记
     * @throws IOException
     */
    @RequestMapping(value = "/uncheck/imageCode/{pageId}")
    public void getImageCode(@PathVariable String pageId) throws IOException {
        if (StringUtils.isBlank(pageId)) {
            logger.error("生成图片验证码时，pageId不能为空");
            response.sendRedirect(ERROR_PAGE);
            return;
        }

        // 在内存中创建图象
        int width = 65, height = 20;
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        // 获取图形上下文
        Graphics g = image.getGraphics();
        // 生成随机类
        Random random = new Random();
        // 设置随机种子
        random.setSeed(new Date().getTime());
        // 设定背景色
        g.setColor(getRandColor(230, 255));
        g.fillRect(0, 0, 100, 25);
        // 设定字体
        g.setFont(new Font("Arial", Font.CENTER_BASELINE | Font.ITALIC, 18));
        // 产生0条干扰线，
        g.drawLine(0, 0, 0, 0);
        // 取随机产生的认证码(4位数字)
        String sRand = "";
        for (int i = 0; i < 4; i++) {
            String rand = String.valueOf(random.nextInt(10));
            sRand += rand;
            // 将认证码显示到图象中
            g.setColor(getRandColor(100, 150));// 调用函数出来的颜色相同，可能是因为种子太接近，所以只能直接生成
            g.drawString(rand, 15 * i + 6, 16);
        }
        for (int i = 0; i < (random.nextInt(5) + 5); i++) {
            g.setColor(new Color(random.nextInt(255) + 1, random.nextInt(255) + 1, random.nextInt(255) + 1));
            g.drawLine(random.nextInt(100), random.nextInt(30), random.nextInt(100), random.nextInt(30));
        }
        
        String key = pageId + "_imageCode";
        // 将验证码存入页面KEY值的SESSION里面
        request.getSession().setAttribute(key, sRand);
        // 图象生效
        g.dispose();
        // 设置请求头参数
        response.setHeader("Cache-Control", "no-store");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");
        ServletOutputStream responseOutputStream = null;
        try {
            responseOutputStream = response.getOutputStream();
            // 输出图象到页面
            ImageIO.write(image, "JPEG", responseOutputStream);
            // 以下关闭输入流！
            responseOutputStream.flush();
        } catch (Exception e) {
            logger.error("生成图片验证码出错！", e);
        } finally {
            if (responseOutputStream != null) {
                try {
                    responseOutputStream.close();
                } catch (IOException ei) {
                    logger.error("生成图片验证码,关闭流出错！", ei);
                }
            }
        }
        
    }
    
    /**
     * 给定范围获得随机颜色
     *
     * @param fc
     * @param bc
     * @return
     */
    private Color getRandColor(int fc, int bc) {
        Random random = new Random();
        if (fc > 255) {
            fc = 255;
        }
        if (bc > 255) {
            bc = 255;
        }
        int r = fc + random.nextInt(bc - fc);
        int g = fc + random.nextInt(bc - fc);
        int b = fc + random.nextInt(bc - fc);
        return new Color(r, g, b);
    }
}
